package com.linchuan.concurrency;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.linchuan.concurrency.ThreadPerTaskWebServer.handleRequest;

public class LifecycleWebServer {

  private final Logger logger = Logger.getLogger(this.getClass().getName());
  private final int NTHREADS = Runtime.getRuntime().availableProcessors() * 8;
  private final ExecutorService exec = Executors.newFixedThreadPool(NTHREADS);

  public void start() throws IOException {
    ServerSocket socket = new ServerSocket(8081);
    while (!exec.isShutdown()) {
      try {
        final Socket conn = socket.accept();
        exec.execute(() -> handleRequest(conn));
      } catch (RejectedExecutionException e) {
        if (!exec.isShutdown()) logger.log(Level.WARNING, "task submission rejected", e);
      }
    }
  }

  public void stop() {
    exec.shutdown();
  }
}
